<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
    <div class="max-w-3xl mx-auto px-4">
      <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-8">确认订单</h1>

      <div v-if="loading" class="text-center py-12">
        <Icon name="line-md:loading-loop" class="w-12 h-12 text-blue-600 mx-auto" />
        <p class="mt-4 text-gray-600 dark:text-gray-400">加载中...</p>
      </div>

      <div v-else-if="order" class="space-y-6">
        <!-- 订单信息 -->
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">订单信息</h2>
          <div class="space-y-3">
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">套餐名称：</span>
              <span class="font-medium text-gray-900 dark:text-white">{{ order.planName }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">订阅时长：</span>
              <span class="font-medium text-gray-900 dark:text-white">{{ order.duration }} 个月</span>
            </div>
            <div class="flex justify-between text-lg">
              <span class="text-gray-600 dark:text-gray-400">应付金额：</span>
              <span class="font-bold text-red-600">¥{{ order.totalPrice }}</span>
            </div>
          </div>
        </div>

        <!-- 支付方式选择 -->
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">选择支付方式</h2>
          <div class="space-y-3">
            <label
              v-for="method in paymentMethods"
              :key="method.value"
              class="flex items-center p-4 border-2 rounded-lg cursor-pointer transition-colors"
              :class="selectedMethod === method.value ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/20' : 'border-gray-200 dark:border-gray-700 hover:border-blue-300'"
            >
              <input
                v-model="selectedMethod"
                type="radio"
                :value="method.value"
                class="w-5 h-5 text-blue-600"
              />
              <div class="ml-3 flex-1">
                <div class="flex items-center gap-2">
                  <Icon :name="method.icon" class="w-6 h-6" />
                  <span class="font-medium text-gray-900 dark:text-white">{{ method.label }}</span>
                </div>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">{{ method.desc }}</p>
              </div>
            </label>
          </div>
        </div>

        <!-- 确认支付按钮 -->
        <div class="flex gap-4">
          <button
            @click="goBack"
            class="flex-1 px-6 py-3 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
          >
            返回
          </button>
          <button
            @click="handlePay"
            :disabled="paying"
            class="flex-1 px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:from-blue-700 hover:to-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-medium"
          >
            {{ paying ? '处理中...' : '确认支付' }}
          </button>
        </div>
      </div>

      <div v-else class="text-center py-12">
        <Icon name="heroicons:exclamation-circle" class="w-16 h-16 text-red-500 mx-auto" />
        <p class="mt-4 text-gray-600 dark:text-gray-400">订单不存在</p>
        <button
          @click="goBack"
          class="mt-4 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          返回
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const $api = useNuxtApp().$api
const toast = useToast()

const order = ref<any>(null)
const loading = ref(true)
const paying = ref(false)
const selectedMethod = ref('wechat_native')

const paymentMethods = [
  {
    value: 'wechat_native',
    label: '微信支付',
    icon: 'ri:wechat-pay-fill',
    desc: '扫码支付，安全便捷'
  },
  // ⚠️ 已隐藏支付宝支付入口（测试阶段）
  // {
  //   value: 'alipay_page',
  //   label: '支付宝',
  //   icon: 'ri:alipay-fill',
  //   desc: '支付宝扫码或跳转支付'
  // }
]

onMounted(async () => {
  const planType = route.query.planType as string
  const duration = route.query.duration as string

  if (!planType || !duration) {
    await router.push('/pricing')
    return
  }

  try {
    // 从订阅计划列表获取计划信息
    const plans = await $api('/subscriptions/plans') as any[]
    const selectedPlan = plans.find(p => p.type === planType && p.duration === parseInt(duration))
    
    if (!selectedPlan) {
      toast.error('未找到对应的订阅计划')
      await router.push('/pricing')
      return
    }

    // 暂存计划信息，等待用户选择支付方式后再创建订单
    order.value = {
      plan: selectedPlan,
      subscriptionType: selectedPlan.type,
      duration: selectedPlan.duration,
      planName: selectedPlan.name,
      totalPrice: selectedPlan.price,
    }
  } catch (error) {
    console.error('加载订单信息失败:', error)
    toast.error('加载订单信息失败，请重试')
    await router.push('/pricing')
  } finally {
    loading.value = false
  }
})

const handlePay = async () => {
  if (!order.value) return

  paying.value = true
  try {
    // 将前端的支付方式映射为后端枚举值
    const paymentMethodMap: Record<string, string> = {
      'wechat_native': 'wechat',
      'alipay_page': 'alipay'
    }
    
    const paymentMethod = paymentMethodMap[selectedMethod.value] || 'wechat'

    // 创建订单
    const createdOrder = await $api('/orders', {
      method: 'POST',
      body: {
        subscriptionType: order.value.subscriptionType,
        duration: order.value.duration,
        paymentMethod: paymentMethod
      }
    }) as any

    // 跳转到支付页面
    await router.push({
      path: `/order/pay/${createdOrder.id}`,
      query: { method: selectedMethod.value }
    })
  } catch (error: any) {
    console.error('创建订单失败:', error)
    toast.error(error?.data?.message || '创建订单失败，请重试')
  } finally {
    paying.value = false
  }
}

const goBack = () => {
  router.back()
}
</script>




